﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class AVPIncomeForm : Form
    {
        const string categoryName = "IncomeType";

        public AVPIncomeForm()
        {
            InitializeComponent();
        }

        // выташить все типы поступлений. а сами поступления определить в перечисления.


        int regID, avpID;

        tb_debt debt;
        tb_AVPIncome avpIncome;



        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                int m = cbMonth.SelectedIndex + 1;
                int y = Convert.ToInt32(cbYear.Text);
                ShowState(avpID, m, y);
                //avpIncome = DBClass.AVPIncomes.Where(wh => wh.AVPID == avpID && )
            }
        }

        private void ShowState(int avpID, int month, int year)
        {
            if (avpID > 0)
            {
                var Inc = DBClass.AVPIncomes
                    .Where(wh => wh.AVPID == avpID && wh.Date.Month == month && wh.Date.Year == year)
                    .Select(se => new
                    {
                        IncomeType = UtilClass.GetCategoryDisplayName(se.IncomeType, categoryName),
                        Amount = se.Amount
                    })
                    .ToList();
                dgvIncome.DataSource = Inc;

                if (InformationClass.Lang)
                {
                    dgvIncome.Columns["IncomeType"].HeaderText = "Вид Поступлений";
                    dgvIncome.Columns["Amount"].HeaderText = "Количество (тыс.сум)";
                }
                else
                {
                    dgvIncome.Columns["IncomeType"].HeaderText = "Киримлар тури";
                    dgvIncome.Columns["Amount"].HeaderText = "Қиймати (минг сўм)";
                }

                debt = DBClass.Debts
                    .Where(wh => wh.AVPID == avpID && wh.Date.Month == month && wh.Date.Year == year)
                    .SingleOrDefault();

                if (debt != null)
                {
                    tbCredit.Text = debt.Credit.Value.ToString("N0");
                    tbDebet.Text = debt.Debet.Value.ToString();
                    tbFact.Text = debt.Fact.Value.ToString();
                }
            }
        }

        private void AVPIncomeForm_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            string[] month;
            if (InformationClass.Lang)
                month = new string[] { "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" };
            else
                month = new string[] { "Январ", "Феврал", "Март", "Апрел", "Май", "Июн", "Июл", "Август", "Сентябр", "Октябр", "Ноябр", "Декабр" };

            cbMonth.SelectedIndexChanged -= cbMonth_SelectedIndexChanged;
            for (int i = 1; i <= 12; i++)
            {
                var m = new
                {
                    ID = i,
                    Name = month[i - 1]
                };
                cbMonth.Items.Add(m);
            }
            cbMonth.DisplayMember = "Name";
            cbMonth.ValueMember = "ID";

            cbYear.SelectedIndexChanged -= cbYear_SelectedIndexChanged;
            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbMonth.SelectedIndex = cbMonth.FindStringExact(month[DateTime.Now.Month - 1]);
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());

            cbIncomeType.DataSource = UtilClass.FillCBCategory(categoryName);
            cbIncomeType.DisplayMember = "Name";
            cbIncomeType.ValueMember = "ID";

            cbMonth.SelectedIndexChanged += new EventHandler(cbMonth_SelectedIndexChanged);
            cbYear.SelectedIndexChanged += new EventHandler(cbYear_SelectedIndexChanged);

        }

        private void buttonDebtAdd_Click(object sender, EventArgs e)
        {
            if (avpID > 0)
            {
                decimal fact, credit, debet;
                int month, year;
                month = cbMonth.SelectedIndex + 1;
                year = Convert.ToInt32(cbYear.Text);


                if (tbFact.Text.GetDecimalOrDefault(out fact) &&
                    tbDebet.Text.GetDecimalOrDefault(out debet) &&
                    tbCredit.Text.GetDecimalOrDefault(out credit))
                {
                    debt = DBClass.Debts.Where(wh => wh.AVPID == avpID && wh.Date.Month == month && wh.Date.Year == year).SingleOrDefault();
                    if (debt != null)
                    {
                        debt.Debet = debet;
                        debt.Fact = fact;
                        debt.Credit = credit;
                    }
                    else
                    {
                        DateTime dt = new DateTime(year, month, 1);
                        debt = new tb_debt
                        {
                            AVPID = avpID,
                            Credit = credit,
                            Date = dt,
                            Debet = debet,
                            Fact = fact
                        };
                        DBClass.Debts.InsertOnSubmit(debt);
                    }
                    try
                    {
                        DBClass.RESPContext.SubmitChanges();
                        MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                    }
                    catch
                    {
                        MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                    }

                }
                else
                {

                    if (InformationClass.Lang)
                        MessageBox.Show("Не вверо введены данные задолженостей или фактически оказанных услуг", "Ошибка", MessageBoxButtons.OK);
                    else
                        MessageBox.Show("Қарздорликлар ёки амалга оширилган хизматлар бўйича маълумотлар нотўғри киритилган", "Хато", MessageBoxButtons.OK);
                    return;
                }
            }
        }

        private void buttonDebtCancel_Click(object sender, EventArgs e)
        {
            if (debt != null)
            {
                tbCredit.Text = debt.Credit.Value.ToString();
                tbDebet.Text = debt.Debet.Value.ToString();
                tbFact.Text = debt.Fact.Value.ToString();
            }
        }

        private void buttonAddIncome_Click(object sender, EventArgs e)
        {
            if (avpID > 0)
            {
                int month, year;
                month = cbMonth.SelectedIndex + 1;
                year = Convert.ToInt32(cbYear.Text);

                DateTime dt = new DateTime(year, month, 1);
                decimal amount;
                if (cbIncomeType.SelectedIndex >= 0 && tbAmaunt.Text.GetDecimalOrDefault(out amount))
                {
                    int incType = Convert.ToInt32(cbIncomeType.SelectedValue);
                    avpIncome = DBClass.AVPIncomes
                        .Where(wh => wh.AVPID == avpID && wh.Date.Month == month && wh.Date.Year == year && wh.IncomeType == incType).SingleOrDefault();
                    if (avpIncome != null)
                    {
                        avpIncome.Amount = amount;
                    }
                    else
                    {
                        avpIncome = new tb_AVPIncome
                        {
                            Amount = amount,
                            AVPID = avpID,
                            Date = dt,
                            IncomeType = incType
                        };
                        DBClass.AVPIncomes.InsertOnSubmit(avpIncome);

                    }
                    try
                    {
                        DBClass.RESPContext.SubmitChanges();
                        MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                        ShowState(avpID, month, year);
                        tbAmaunt.Text = string.Empty;
                    }
                    catch
                    {
                        MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                    }

                }
                else
                {
                    if (InformationClass.Lang)
                        MessageBox.Show("Не верно введено количество вида поступления", "Ошибка", MessageBoxButtons.OK);
                    else
                        MessageBox.Show("Киримлар турлари сони нотўғри киритилган", "Хато", MessageBoxButtons.OK);
                    return;
                }
            }
        }

        private void cbMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            int m = cbMonth.SelectedIndex + 1;
            int y = Convert.ToInt32(cbYear.Text);
            ShowState(avpID, m, y);
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            int m = cbMonth.SelectedIndex + 1;
            int y = Convert.ToInt32(cbYear.Text);
            ShowState(avpID, m, y);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
